package com.saohuobang.test.service;

import com.google.common.base.Objects;
import com.saohuobang.test.listener.PropertyFileListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

import static com.saohuobang.test.util.PropertyUtil.checkBusinessRootDir;
import static com.saohuobang.test.util.PropertyUtil.checkFileType;

/**
 * 作者 yaohua.liu
 * 日期 2015-12-21 14:33
 * 包名 com.saohuobang.test.service
 * 说明 ...
 */
public class MonitorThread extends Thread{
    private static final Logger logger = LoggerFactory.getLogger(MonitorThread.class);
    private PropertyFileListener listener;
    private WatchService watchService;
    private FrameworkService frameworkService;

    public MonitorThread(PropertyFileListener listener, WatchService watchService, FrameworkService frameworkService){
        this.listener = listener;
        this.watchService = watchService;
        this.frameworkService = frameworkService;
    }

    @Override
    public void run() {
        logger.info("start monitor,thread name = {}",Thread.currentThread().getName());
        while (true) {
            List<WatchEvent<?>> events = null;
            WatchKey wk = null;
            try {
                wk = watchService.take();
                events = wk.pollEvents();
            } catch (InterruptedException e) {
                logger.error("注册监听的路径失败:msg = {}", e.getMessage(), e);
                break;
            }
            for (WatchEvent<?> event : events) {
                // final Path changed = (Path) event.context();
                String fileName = event.context().toString();
                String kind = event.kind().name();
                logger.info("监听到文件有修改,file_name = {},操作类型 = {}", fileName, kind);
                if (Objects.equal(kind, "ENTRY_CREATE") && (checkBusinessRootDir(fileName) || checkFileType(fileName))) {
                    logger.info("重启test 服务。。。。。。");
                    if (frameworkService != null) {
                        frameworkService.restart();
                    }
                    logger.info("stop monitor,thread name = {}",Thread.currentThread().getName());
                    return;
                }
            }
            // reset the key
            boolean valid = wk.reset();
            if (!valid) {
                logger.info("Key has been unregisterede");
            }
        }
    }
}
